import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:mmkv/mmkv.dart';
import 'package:permission_handler/permission_handler.dart';

import '../../../checkupdate/update_service.dart';
import '../../../constants.dart';
import '../../../models/user_info_entity.dart';

class MainLogic extends GetxController {
  var currentIndex = 0.obs;
  var title = ''.obs;

  final MMKV mmkv = MMKV.defaultMMKV();

  var permissions = [
    Permission.location,
    Permission.photos,
  ];

  void changePage(int index) {
    currentIndex.value = index;
  }

  @override
  void onInit() {
    super.onInit();

    _getUserInfo();
    checkPermission();

    WidgetsBinding.instance.addPostFrameCallback((_) async {
      await UpdateService.doCheckForUpdates();
    });
  }

  void checkPermission() async {
    var statuses = await permissions.request();

    for (var element in statuses.keys) {
      if (statuses[element]!.isDenied) {
        requestPermission(element);
      } else if (statuses[element]!.isPermanentlyDenied) {
      } else if (statuses[element]!.isRestricted) {
      } else {
        requestPermission(element);
      }
    }
  }

  void requestPermission(Permission permission) async {
    await permission.request();
  }

  void _getUserInfo() {
    UserInfoEntity? userInfo =
        UserInfoEntity.fromJson(jsonDecode(mmkv.decodeString(kKeyUser)!));
    title.value = userInfo.targetSite?.name ?? '师付';
  }
}
